import fastapi.params
from fastapi import Form
from src.core.session import *
from src.entity.models import Api, UpdateApi, CreateApi, BasicModel
from src.core.logconfig import log
from src.common.response import success_response, fail_response
from src.common.status import CLASS_STATUS
from src.utils.tools import get_cur_time
from src.common.base_service import BaseService
from src.common.base_router import BaseRouter

log = log.logger
sc = SQLCON

api = BaseRouter(
    entity=Api,
    create_schema=CreateApi,
    update_schema=UpdateApi,
    out_schema=Api,
    prefix="/sys/api",
    tags=["API"]
).router

api_service = BaseService(Api)

async def query_all():
    return api_service.get_list()

async def query_one(id):
    return api_service.get_by_id(id)


async def create(
    name: str = Form(),
    method: str = Form(default='get'),
    path: str = Form(default='/'),
    content: str = Form(default='{}'),
    group: str = Form(default=None),
    project: str = Form(default=None),
    version: str = Form(default=None),
    desc: str = Form(default=None),
    state: int = Form(default=1)):
    
    create_data = CreateApi(
        name=name,
        method=method,
        path=path,
        content=content,
        group=group,
        project=project,
        version=version,
        desc=desc,
        state=state,
        create_time=get_cur_time()
    )
    print(f"创建api数据: {create_data}")
    return api_service.create(create_data)


async def update(
        id: int = Form(),
        name: str = Form(),
        method: str = Form(),
        path: str = Form(default='/'),
        content: str = Form(default='{}'),
        group: str = Form(default=None),
        project: str = Form(default=None),
        version: str = Form(default=None),
        desc: str = Form(default=None),
        state: int = Form(default=1),
    ):
    update_data = UpdateApi(
        id=id,
        name=name,
        method=method,
        path=path,
        content=content,
        group=group,
        project=project,
        version=version,
        desc=desc,
        state=state,
        update_time=get_cur_time()
    )
    return api_service.update(update_data)

async def delete_one(data: BasicModel):
    delete_data = UpdateApi(
        id=data.id,
        status=CLASS_STATUS["STATE_DELETED"],
        update_time=get_cur_time())
    # 更新数据为删除状态
    return api_service.delete(delete_data)
